package com.example.everying.task;

import com.example.everying.constant.OrderConstants;
import com.example.everying.model.entity.content.ActivityApply;
import com.example.everying.model.entity.content.ActivityArticle;
import com.example.everying.model.entity.user.UserBalanceEntity;
import com.example.everying.model.entity.user.UserBalanceTransactionEntity;
import com.example.everying.service.content.impl.ActivityApplyServiceImple;
import com.example.everying.service.content.impl.ActivityArticleServiceImple;
import com.example.everying.service.user.UserBalanceService;
import com.example.everying.service.user.UserBalanceTransactionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
@Slf4j
public class ActivityArticleStatusTask {
    private static final String PLATFORM_USER_ID = "1"; // 平台用户ID

    // 检查订单完成状态, 超时三天打款
    @Autowired
    private ActivityApplyServiceImple activityApplyService;
    @Autowired
    private ActivityArticleServiceImple activityArticleService;
    @Autowired
    private UserBalanceService userBalanceService;
    @Autowired
    private UserBalanceTransactionService userBalanceTransactionService;

    @Scheduled(cron = "0 0 0/1 * * ?")
    public void checkOrderStatus() {
        log.info("开始检查订单进行中状态");
        List<ActivityArticle> activityArticles = activityArticleService.getArticleByStatus("1");
        if (activityArticles.isEmpty()) {
            log.info("没有进行中的订单");
            return;
        }
        List<String> articleIds = activityArticles.stream().map(ActivityArticle::getId).toList();
        Map<String, ActivityArticle> articleMap = activityArticles.stream().collect(Collectors.toMap(ActivityArticle::getId, activityArticle -> activityArticle));
        List<ActivityApply> activityApplies = activityApplyService.getApplyListByArticleIds(articleIds);
        activityApplies.forEach(activityApply -> {
            if (activityApply.getOrdersStatus().equals("3")) {
                log.info("订单已完成");
                // 判断付款人
                // 判断接单完成时间是否超过三天
                if (activityApply.getAcceptedAt().isAfter(activityApply.getAcceptedAt().plusDays(3))) {
                    log.info("订单已完成三天开始打款");
                    ActivityArticle activityArticle = articleMap.get(activityApply.getArtId());
                    if (activityArticle  != null) {
                        handleOrderCompleted(activityArticle);
                        log.info("文章ID:{} 订单已完成打款完成",  activityArticle.getId());
                    }

                }
            }
        });

        log.info("开始检查订单完成状态");
        List<ActivityArticle> activityArticles2 = activityArticleService.getArticleByStatus("3");
        if (activityArticles2.isEmpty()) {
            log.info("没有完成的订单");
            return;
        }
        List<String> articleIds2 = activityArticles2.stream().map(ActivityArticle::getId).toList();
        Map<String, ActivityArticle> articleMap2 = activityArticles2.stream().collect(Collectors.toMap(ActivityArticle::getId, activityArticle -> activityArticle));
        List<ActivityApply> activityApplies2 = activityApplyService.getApplyListByArticleIds(articleIds2);
        activityApplies2.forEach(activityApply -> {
                // 判断付款人
                // 判断接单完成时间是否超过三天
                if (activityApply.getAcceptedAt().isAfter(activityApply.getAcceptedAt().plusDays(3))) {
                    log.info("订单已完成三天开始打款");
                    ActivityArticle activityArticle = articleMap2.get(activityApply.getArtId());
                    if (activityArticle  != null) {
                        handleOrderCompleted(activityArticle);
                        log.info("文章ID:{} 订单已完成打款完成",  activityArticle.getId());
                    }
                }
        });

    }

    private void handleOrderCompleted(ActivityArticle activityArticle) {
        log.info("处理已完成状态的订单");
        String userId = getRecipientUserId(activityArticle);
        BigDecimal amount = activityArticle.getMoney();
        String userType = activityArticle.getType() == 1 ? "买家" : "卖家";

        log.info("开始打款，给{}打款,用户id{}", userType, userId);

        boolean isAdded = userBalanceService.addBalance(userId, amount);
        if (isAdded) {
            UserBalanceEntity userBalance = userBalanceService.getBalanceByUserId(userId);
            createAndSaveTransaction(
                    userId,
                    activityArticle.getId(),
                    amount,
                    userBalance.getAvailableAmount().add(amount),
                    OrderConstants.TYPE_USER_INCOME,
                    "用户收款",
                    OrderConstants.USER_TYPE_USER
            );
        }

        // 系统用户扣款
        log.info("开始扣款，给系统扣款");
        boolean isDeducted = userBalanceService.deductBalance(PLATFORM_USER_ID, amount);
        if (isDeducted) {
            UserBalanceEntity platformBalance = userBalanceService.getBalanceByUserId(PLATFORM_USER_ID);
            createAndSaveTransaction(
                    PLATFORM_USER_ID,
                    activityArticle.getId(),
                    amount,
                    platformBalance.getAvailableAmount().subtract(amount),
                    OrderConstants.TYPE_PLATFORM_EXPENSE,
                    "用户收款",
                    OrderConstants.USER_TYPE_PLATFORM
            );
        }
    }

    // 公共方法：创建并保存交易记录
    private void createAndSaveTransaction(String userId, String txId, BigDecimal changeAmount, BigDecimal balanceAfterChange,
                                          String txType, String remark, String userType) {
        log.info("开始保存交易记录，用户id{},业务id{},交易类型{}，用户类型{}", userId, txId, txType, userType);
        UserBalanceTransactionEntity transaction = new UserBalanceTransactionEntity();
        transaction.setUserId(userId);
        transaction.setTxId(userType.equals(OrderConstants.USER_TYPE_PLATFORM) ? "PL" + txId : txId);
        transaction.setChangeAmount(changeAmount);  // 微信单位为分
        transaction.setBalanceSnapshot(balanceAfterChange);
        transaction.setTxStatus(OrderConstants.TX_STATUS_SUCCESS);
        transaction.setTxType(txType);
        transaction.setRemark(remark);
        transaction.setUserType(userType);
        boolean result = userBalanceTransactionService.save(transaction);
        log.info("保存交易结果：{}", result ? "成功" : "失败");
    }

    /**
     * 获取收款用户的ID
     * 根据活动类型判断是买家还是卖家
     *
     * @param activityArticle 活动文章对象，包含用户ID和活动类型
     * @return 收款用户的ID
     */
    private String getRecipientUserId(ActivityArticle activityArticle) {
        return activityArticle.getType() == 1 ? activityArticle.getUserId() : activityArticle.getApplyId();
    }
}
